/* Ekeko - Server based resource loader
 * Copyright (C) 2013 Jorge Luis Zapata
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.
 * If not, see <http://www.gnu.org/licenses/>.
 */
#include "Ekeko.h"
#include "ekeko_private.h"
/*============================================================================*
 *                                  Local                                     *
 *============================================================================*/
/*============================================================================*
 *                                 Global                                     *
 *============================================================================*/
/*============================================================================*
 *                                   API                                      *
 *============================================================================*/
EAPI Ekeko_Context * ekeko_context_new(const char *name, uint32_t max_size)
{
	Ekeko_Context *thiz;
	Ekeko_Msg_Context_Get msg;
	Ekeko_Msg_Context_Get_Reply r = { 0 };
	Eshm_Segment *s;
	Eix_Error err = { 0 };

	msg.name = (char *)name;
	msg.size = max_size;

	eix_server_message_send(ekeko_server, EKEKO_MSG_CONTEXT_GET, &msg, &r, &err, NULL);
	if (eix_error_is_set(&err))
	{
		ERR("Failed with error code %d and message '%s'", err.code, err.msg);
		goto err;
	}
	/* common check */
	if (!r.size) goto err;
	/* posix check */
	if (!r.name) goto err;

	/* get the segment from the reply */
	s = eshm_segment_posix_new(r.name, EINA_FALSE, r.size);
	if (!s) goto err;

	thiz = calloc(1, sizeof(Ekeko_Context));
	thiz->name = strdup(name);
	thiz->size = r.size;
	thiz->id = r.id;
	thiz->s = s;

	return thiz;
err:

	if (r.name)
		free(r.name);
	if (err.msg)
		free(err.msg);
	return NULL;
}

EAPI const char * ekeko_context_name_get(Ekeko_Context *thiz)
{
	if (!thiz) return NULL;
	return thiz->name;
}

EAPI uint32_t ekeko_context_size_get(Ekeko_Context *thiz)
{
	if (!thiz) return 0;
	return thiz->size;
}

EAPI void ekeko_context_free(Ekeko_Context *thiz)
{
	Ekeko_Msg_Context_Free msg;

	if (!thiz) return;

	msg.id = thiz->id;
	eix_server_message_send(ekeko_server, EKEKO_MSG_CONTEXT_FREE, &msg, NULL, NULL, NULL);
}
